package com.dragon.app.commons.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Properties;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.marvels.common.utils.MarvelsLogUtil;

import sun.misc.BASE64Decoder;

@Component
public class FileDragonUtils {
	
	private static String configPropertiesPath;
	
	
	public  String getConfigPropertiesPath() {
		return configPropertiesPath;
	}
	
	@Value("${config.properties.path}")
	public  void setConfigPropertiesPath(String configPropertiesPath) {
		FileDragonUtils.configPropertiesPath = configPropertiesPath;
	}
	
	/**
	 * 根据参数 url 来返回对应的网页源代码  
	 * 多用于返回静态的html页面
	 * @param url
	 * @return
	 */
	public static String getHTMLFromUrl(String url) {
		CloseableHttpClient http = HttpClients.custom().build();
		HttpGet httpget = null;
		httpget = new HttpGet(url);  
		HttpEntity entity = null;
		InputStream content = null;
		try {
			CloseableHttpResponse execute = http.execute(httpget);
			entity = execute.getEntity();
			content = entity.getContent();
		} catch (IOException e) {
			MarvelsLogUtil.getInstance().error("=====ERROR=====", e);
		}
		return com.dragon.app.commons.utils.IODeagonAppUtils.convertStreamToString(content);
	}
	
	public static void main(String[] args) {
		String htmlFromUrl = getHTMLFromUrl("http://10.0.17.11/signature/protocol.html");
		System.out.println(htmlFromUrl);
	}
	
	/**
	 * base64转换PDF
	 * @param base64sString
	 * @param file
	 */
	@SuppressWarnings("restriction")
	public static void base64ToPDF(String base64sString, File file) {
		BufferedInputStream bin = null;
		FileOutputStream fout = null;
		BufferedOutputStream bout = null;
		BASE64Decoder decoder = new sun.misc.BASE64Decoder();
		try {
			byte[] bytes = decoder.decodeBuffer(base64sString);
			ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
			// 创建从底层输入流中读取数据的缓冲输入流对象
			bin = new BufferedInputStream(bais);
			// 创建到指定文件的输出流
			fout = new FileOutputStream(file);
			// 为文件输出流对接缓冲输出流对象
			bout = new BufferedOutputStream(fout);
			byte[] buffers = new byte[1024];
			int len = bin.read(buffers);
			while (len != -1) {
				bout.write(buffers, 0, len);
				len = bin.read(buffers);
			}
			// 刷新此输出流并强制写出所有缓冲的输出字节，必须这行代码，否则有可能有问题
			bout.flush();
		} catch (IOException e) {
			MarvelsLogUtil.getInstance().error("=====ERROR=====", e);
		} finally {
			try {
				if(bin != null) { bin.close();}
				if(fout != null) {fout.close();}
				if(bout != null) {bout.close();}
			} catch (IOException e) {
				MarvelsLogUtil.getInstance().error("=====ERROR=====", e);
			}
		}
	}
	
	/**
	 * 每次动态的获取properties文件的value值
	 * 
	 * @param key
	 * @return
	 */
	public static String getValueByPropertiesKey(String key){
		InputStream inputStream=null;
		Properties properties=null;
		try {
			String filePath=configPropertiesPath + File.separator +"common.properties";
			File loadFile = new File(filePath);
			inputStream = new FileInputStream(loadFile);
			properties = new Properties();
			properties.load(inputStream);
		} catch (IOException e) {
			MarvelsLogUtil.getInstance().error("=====ERROR=====", e);
		} finally {
			try {
				if(inputStream != null){
					inputStream.close();
				}
			} catch (IOException e) {
				MarvelsLogUtil.getInstance().error("=====ERROR=====", e);
			}
		}
		String value = properties.getProperty(key);
		properties = null;
		return value;
	}
	
	
	/**
	 * 每次动态的获取properties文件的value值
	 * @param key
	 * @return
	 */
	public static String getValueByPropertiesKey(String key, String propertiesName){
		Properties properties =null;
		InputStream inputStream=null;
		try {
			String filePath=configPropertiesPath+ File.separator+propertiesName;
			File loadFile = new File(filePath);
			inputStream = new FileInputStream(loadFile);
			properties = new Properties();
			properties.load(inputStream);
		} catch (IOException e) {
			MarvelsLogUtil.getInstance().error("=====ERROR=====", e);
		} finally {
			try {
				if(inputStream != null){
					inputStream.close();
				}
			} catch (IOException e) {
				MarvelsLogUtil.getInstance().error("=====ERROR=====", e);
			}
		}
		String value = properties.getProperty(key);
		properties = null;
		return value;
	}
	
	/**
	 * 将String字符串写入文件夹中
	 * （*） 为必填项
	 * @param data  需要写入的数据  *
	 * @param path  写入的路径          *
	 */
	public static void stringToFile(String data ,File file){
		if(!file.getParentFile().exists()){
			file.getParentFile().mkdirs();
		}
		FileOutputStream os = null;
		try {
			os = new FileOutputStream(file);
			ByteArrayInputStream in = new ByteArrayInputStream(data.getBytes());
			IOUtils.copy(in, os);
		} catch (IOException e) {
			MarvelsLogUtil.getInstance().error("=====ERROR=====", e);
		} finally {
			if(os != null){
				try {
					os.close();
				} catch (IOException e) {
					MarvelsLogUtil.getInstance().error("=====ERROR=====", e);
				}
			}
		}
	} 
	
	/**
	 * 获取带有规则的前缀    /yyyy/xx/xx
	 */
	public static String getPathPrefix(){
		Calendar calendar = Calendar.getInstance();
	    int day = calendar.get(Calendar.DATE);
	    int month = calendar.get(Calendar.MONTH) + 1;
	    int year = calendar.get(Calendar.YEAR);
		StringBuffer prefix = new StringBuffer();
		prefix.append("/")
			  .append(year)
			  .append("/")
			  .append(month)
			  .append("/")
			  .append(day);
		return prefix.toString();
	}
}
